package siedler.GUI.gameElements;

import java.util.ArrayList;

import util.simpleIO.Out;

public class ConnectionList {
	
//	public static void main(String[] args) {
//		
//		Field.gamePanel = new SiedlerGamePanel("blaa");
//		Field f1 = new Field();
//		Field f2 = new Field();
//		Field f3 = new Field();
//		
//		ConnectionList list = new ConnectionList();
//		
//		Out.pl( list.addConnection(new Connection(f1,f2)) );
//		Out.pl( list.addConnection(new Connection(f1,f3)) );
//		Out.pl( list.addConnection(new Connection(f1,f1)) );
//		Out.pl( list.addConnection(new Connection(f3,f1)) );
//	}
	
	
	private ArrayList<Connection> connections = new ArrayList<Connection>();	// list of all connections
	
	/**
	 * getConnections
	 * @return all connections
	 */
	public Connection[] getConnections(){
		return connections.toArray(new Connection[0]);
	}
	
	/**
	 * addConnection
	 * @param c
	 * @return 	Added:     'c', the connection that was added.
	 * 			Not Added: the existing, equivalent connection.
	 */
	public Connection addConnection(Connection c){
		
		if(connections.contains(c)){
			//Out.pl("> Contained ... " + c);
			return getConnection(c.field1, c.field2);
		}
		
		//Out.pl("> New ... " + c);
		connections.add(c);
		return c;
	}
	
	/**
	 * getConnection - doesn't return all single field connections!
	 * @param f1
	 * @param f2
	 * @return a connection with f1 and f2 OR null.
	 */
	public Connection getConnection(Field f1, Field f2){
		Connection tmpCon = new Connection(f1,f2,0);
		
		for(Connection c : connections){
			if(c.equals(tmpCon))
				return c;
		}
		
		throw new RuntimeException("Connection does not exist!");
		//return null;
	}
	
	/**
	 * isConnected
	 * Similar to contains(c);
	 * @param f1
	 * @param f2
	 * @return true if there is a connection between f1 and f2. (without direction)
	 */
	public boolean isConnected(Field f1, Field f2){
		return connections.contains(new Connection(f1,f2,0));
	}
	/**
	 * contains
	 * Similar to isConnected(f1,f2)
	 * @param tmpCon
	 * @return true if list contains connection. (connection between fields exist)
	 */
	public boolean contains(Connection tmpCon) {
		return connections.contains(tmpCon);
	}

	/**
	 * getConnections
	 * @param f1
	 * @return all connections which contain f1
	 */
	public ArrayList<Connection> getConnections(Field f1){
		
		ArrayList<Connection> ret = new ArrayList<Connection>();
		
		for(Connection c: connections){
			if(f1.equals(c.field1) || f1.equals(c.field2))
				ret.add(c);
		}
		return ret;
	}
	
	/**
	 * initAllConnectionsCoordinates
	 * Graphical initialization for all coordinates
	 */
	public void initAllConnections(){
		
		Out.pl("" + this + "");
		for(Connection c : connections){
			c.initGraphics();
		}
	}
	
	@Override
	public String toString(){
		return "CoordinateList: "+connections.size()+" coordinates";
	}
}
